<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '申请退款',
    navigationBarRightButton: {
      hide: true,
    },
  },
}
</route>
<template>
  <view
    class="w-full h-full bg-white overflow-hidden box-border"
    :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
  >
    <view class="w-full h-full pos-relative z-1 bg-#F6F6F8">
      <wd-navbar @click-left="handleClickLeft">
        <template #title>
          <text class="text-gray-333 font-size-36 font-500">申请退款</text>
        </template>
        <template #left>
          <wd-icon name="chevron-left" class="text-gray-333 font-size-44"></wd-icon>
        </template>
      </wd-navbar>
      <view class="w-full box-border home-content ps-b-180">
        <view class="w-full mg-b-20" v-if="statuType === 'apply'">
          <view class="w-full bg-#FFEBEB p-x-32 p-y-32">
            <view class="font-size-32 text-gray-333 font-500 line-h-44">
              商家驳回，请重新补充信息提交申请
            </view>
            <view class="font-size-28 font-400 text-red-1 mg-t-24">
              *48小时未完成提交，则默认取消申请
            </view>
          </view>
          <view class="w-full p-x-28 p-y-32 bg-white">
            <text class="font-size-24 text-gray-333 font-400 line-h-34">
              驳回原因：{{ rejectReason }}
            </text>
          </view>
        </view>
        <view class="w-full p-x-28 ps-t-32 bg-white">
          <view
            class="w-full flex justify-start mg-b-32 ps-b-32 bdr-bottom-2-#F5F5F5"
            v-for="(item, index) in OrderList"
            :key="index"
          >
            <view class="flex justify-between flex-items-center" v-if="statuType !== 'apply'">
              <wd-checkbox v-model="item.checked" @change="checkChange"></wd-checkbox>
            </view>
            <view class="wr-220 hr-220">
              <wd-img :width="'220rpx'" :height="'220rpx'" :src="item.pic" />
            </view>
            <view class="flex justify-between flex-col product-info">
              <view class="font-size-28 text-gray-333 font-500">{{ item.name }}</view>
              <view class="flex justify-between flex-items-center product-type font-size-24">
                <view>{{ item.title }}</view>
                <!-- <wd-icon name="arrow-down" size="22rpx"></wd-icon> -->
              </view>
              <view class="flex justify-between items-end">
                <view
                  class="flex justify-start items-end font-size-24 line-height-none text-blue-1"
                >
                  <view class="mg-r-4 mg-b-4">¥</view>
                  <view class="font-size-32">{{ item.sku_price }}</view>
                </view>
                <view>
                  <wd-input-number
                    v-model="item.num"
                    :max="item.maxNum"
                    :disabled="statuType === 'apply'"
                  />
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="w-full p-x-28 bg-white">
          <view
            class="w-full flex justify-between items-center bdr-bottom-2-#F5F5F5"
            @click="selectRefundType"
          >
            <view class="flex justify-between items-center p-y-34">退款类型</view>
            <view
              class="flex justify-start items-center font-size-32 font-400 line-h-44"
              :class="{ 'text-gray-ccc': !showParam.refundTypeName }"
            >
              <text>
                {{ showParam.refundTypeName ? showParam.refundTypeName : '请选择' }}
              </text>
              <wd-icon name="chevron-right" custom-class="font-size-40"></wd-icon>
            </view>
          </view>
          <view
            class="w-full flex justify-between items-center bdr-bottom-2-#F5F5F5"
            @click="selectReason"
          >
            <view class="flex justify-between items-center p-y-34">退货理由</view>
            <view
              class="flex justify-start items-center font-size-32 font-400 line-h-44"
              :class="{ 'text-gray-ccc': !postParam.reason }"
            >
              <text>
                {{ postParam.reason ? postParam.reason : '请选择' }}
              </text>
              <wd-icon name="chevron-right" custom-class="font-size-40"></wd-icon>
            </view>
          </view>
          <view>
            <view class="flex justify-between items-center p-y-34">退货说明</view>
            <view class="ps-b-34 bdr-bottom-2-#F5F5F5">
              <wd-textarea placeholder="补充退货说明" v-model="postParam.remark" />
            </view>
          </view>
          <view>
            <view class="flex justify-between items-center p-y-34">上传凭证</view>
            <view class="ps-b-34">
              <wd-upload
                :file-list="fileList"
                image-mode="aspectFill"
                :multiple="true"
                name="file[]"
                :header="header"
                :action="VITE_UPLOAD_BASEURL"
                @change="handleChange"
              ></wd-upload>
            </view>
          </view>
        </view>
        <view
          class="w-full hr-156 ps-t-16 pos-absolute pos-bottom-0 pos-left-0 p-x-28 box-border z-2 b-solid-#F5F5F5-2 bg-white"
        >
          <view class="flex justify-between items-center">
            <view class="flex justify-between items-center">
              <view class="flex justify-between items-center" v-if="statuType !== 'apply'">
                <wd-checkbox v-model="checkedAll" @change="checkChangeAll"></wd-checkbox>
                <view class="font-size-28">全选</view>
              </view>
            </view>
            <view class="flex justify-start flex-items-center">
              <view class="flex justify-start items-center" v-if="showParam.price > 0">
                <view class="mg-r-12 font-size-28">合计</view>
                <view class="flex justify-start flex-items-center">
                  <view class="font-size-24 line-height-none mg-r-6">¥</view>
                  <view class="font-size-36 line-height-none mg-r-24">{{ showParam.price }}</view>
                </view>
              </view>
              <view class="wr-224 hr-80">
                <wd-button type="primary" size="small" @click="reasonSubmit">
                  <text class="font-size-32 line-h-44 font-500">申请退款</text>
                </wd-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <wd-action-sheet v-model="showSelect" :actions="actions" @select="select" />
    <wd-action-sheet v-model="showReason" :actions="ReasonList" @select="ReasonSelect" />
  </view>
</template>

<script lang="ts" setup>
import { getAppConfig } from '@/service/my/my'
import { getOrderDetail, getRefundPage, postRefundApply } from '@/service/order/order'
import { useUserStore } from '@/store/user'
const VITE_UPLOAD_BASEURL = import.meta.env.VITE_UPLOAD_BASEURL
const userStore = useUserStore()
const { token } = userStore.userInfo as unknown as IUserInfo
const header = ref({
  token,
})
defineOptions({
  name: 'ApplyRefund',
})
const checkedAll = ref(false)
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
const handleClickLeft = () => {
  uni.navigateTo({ url: '/pages/shopping/allOrder' })
}
const showSelect: any = ref(false)
const actions = ref([
  {
    name: '退货退款',
    value: 0,
  },
  {
    name: '仅退款',
    value: 1,
  },
])
const selectRefundType = () => {
  showSelect.value = true
}
const postParam: any = ref({
  id: 0, // 订单id 必传
  refundId: null, // 退款订单id 非必传 (再次提交必传)
  refundType: 0, // 退款类型 0=退货退款,1=仅退款 必传
  orderGoodIds: '', // sku id 必传 (再次提交非必传)
  reason: '', // 理由 必填
  remark: '', // 备注 必填
  pics: '', // 凭证图片
})
const showParam: any = ref({
  refundTypeName: '',
  price: 0,
})
const fileList = ref<any[]>([])

function handleChange({ fileList: files }) {
  fileList.value = files
}
const checkChange = () => {
  orderChange()
}
const orderChange = () => {
  let price: any = 0
  let checked: any = 0
  postParam.value.orderGoodIds = ''
  OrderList.value.forEach((item: any) => {
    if (item.checked) {
      price += Number(item.sku_price) * item.num
      checked++
      postParam.value.orderGoodIds += item.sku_id + ','
    }
  })
  postParam.value.orderGoodIds = postParam.value.orderGoodIds.slice(0, -1)
  if (OrderList.value.length === checked) {
    checkedAll.value = true
  } else {
    checkedAll.value = false
  }
  showParam.value.price = price
}
const checkChangeAll = (ev: any) => {
  OrderList.value.map((item: any) => {
    item.checked = ev.value
    return item
  })
  orderChange()
}
const statuType = ref('')
const rejectReason = ref('')
onLoad(() => {})
const OrderList: any = ref([])
const ReasonList: any = ref([])
onShow(() => {
  const orderString: any = uni.getStorageSync('RefundDetails')
  if (orderString) {
    const orderDetail: any = JSON.parse(orderString)
    statuType.value = orderDetail.handleType
    if (orderDetail.handleType === 'refund') {
      getRefundData(orderDetail)
    } else if (orderDetail.handleType === 'apply') {
      getData(orderDetail)
    }
  }
  getAppConfig().then((res: any) => {
    if (res.data) {
      const reasonList = res.data.refund_reason.value.split(',')
      reasonList.forEach((item: any) => {
        ReasonList.value.push({
          name: item,
          value: item,
        })
      })
    }
  })
})
const getRefundData = (order: any) => {
  getOrderDetail(order.id, 0).then((res: any) => {
    postParam.value.id = res.data.order.id
    if (res.data.order.orderGoods) {
      res.data.order.orderGoods.map((m: any) => {
        m.checked = true
        m.maxNum = m.num
        return m
      })
      OrderList.value = res.data.order.orderGoods
      orderChange()
    }
  })
}
const getData = (orderDetail: any) => {
  getOrderDetail(orderDetail.id, 1).then((res: any) => {
    res.data.orderGoods.map((m: any) => {
      m.checked = true
      m.maxNum = m.num
      return m
    })
    OrderList.value = res.data.orderGoods
    rejectReason.value = res.data.refundOrderInfo.reject_reason
    postParam.value.id = res.data.refundOrderInfo.id
    postParam.value.refundId = res.data.refundOrderInfo.refund_type
    postParam.value.reason = res.data.refundOrderInfo.reason
    postParam.value.remark = res.data.refundOrderInfo.remark
    showParam.value.refundTypeName = postParam.value.refundId === 0 ? '退货退款' : '仅退款'
    if (res.data.refundOrderInfo.pics) {
      res.data.refundOrderInfo.pics.split(',').forEach((item: any) => {
        fileList.value.push({
          url: item,
        })
      })
    }
    orderChange()
    postParam.value.orderGoodIds = res.data.refundOrderInfo.order_good_ids
  })
}
const showReason: any = ref(false)
const selectReason = () => {
  showReason.value = true
}

const select = (ev: any) => {
  postParam.value.refundType = ev.item.value
  showParam.value.refundTypeName = ev.item.name
  showSelect.value = false
}
const ReasonSelect = (ev: any) => {
  postParam.value.reason = ev.item.value
  showReason.value = false
}
const reasonSubmit = () => {
  let pics = ''
  fileList.value.forEach((item: any) => {
    pics += item.url + ','
  })
  pics = pics.slice(0, -1)
  postParam.value.pics = pics
  if (postParam.value.reason === '') {
    uni.showToast({
      title: '请选择退货理由',
      icon: 'none',
    })
    return
  }
  if (postParam.value.remark === '') {
    uni.showToast({
      title: '请填写退货说明',
      icon: 'none',
    })
    return
  }
  if (showParam.value.refundTypeName === '') {
    uni.showToast({
      title: '请填写备注',
      icon: 'none',
    })
    return
  }
  postRefundApply(postParam.value).then((res: any) => {
    uni.showToast({
      title: '提交成功',
      icon: 'none',
    })
    const item: any = {
      name: '退款/售后',
    }
    uni.setStorageSync('orderStatus', JSON.stringify(item))
    uni.navigateTo({ url: '/pages/shopping/allOrder' })
  })
}
</script>

<style scoped lang="scss">
.home-content {
  height: calc(100% - var(--wot-navbar-height, 88rpx));
  overflow: auto;
}
.product-card {
  padding-bottom: 32rpx;
  margin-bottom: 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
}
.product-info {
  width: calc(100% - 312rpx);
  margin-left: 20rpx;
  transition: all 0.3s linear;
}
.product-info-checkbox {
  width: calc(100% - 240rpx);
}
.product-type {
  width: 108rpx;
  height: 44rpx;
  padding: 4rpx 16rpx;
  color: #666666;
  background: #f3f4f8;
  border-radius: 8rpx;
}
.product-checkbox {
  box-sizing: border-box;
  width: 40rpx;
  height: 40rpx;
  margin-right: 32rpx;
  border-radius: 50%;
}
.check-border {
  border: 4rpx solid #cccccc;
}
::v-deep .wd-button {
  width: 100% !important;
  height: 100% !important;
}
::v-deep .wd-textarea {
  padding: 0 !important;
}
::v-deep .wd-textarea__value {
  box-sizing: border-box !important;
  padding: 24rpx !important;
  overflow: hidden !important;
  background: #f9f9f9 !important;
  border-radius: 16rpx !important;
}
::v-deep .wd-textarea__inner {
  height: 214rpx !important;
}
</style>
